import { useEffect, useState } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import { useDispatch, useSelector } from 'react-redux';
import { publishArticle, getArticleById } from '@/store/actions';
import { useHistory, useParams } from 'react-router-dom';

import Channel from '@/components/Channel';

import styles from './index.module.scss';
import 'react-quill/dist/quill.snow.css';

const Publish = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  // 获取url查询参数
  const params = useParams();
  // 获取表单实例
  const [form] = Form.useForm();
  // 从redux中获取文章详情
  const articleDetail = useSelector((state) => state.article.article);
  // 上传文件列表
  const [fileList, setFileList] = useState([]);
  // 上传文件列表备份
  const [fileListStore, setFileListStore] = useState([]);
  // 发布类型
  const [publishType, setPublishType] = useState('publish');
  // 上传图片数量
  const [maxCount, setMaxCount] = useState(1);

  // 获取数据
  useEffect(() => {
    if (params.id !== articleDetail.id) {
      console.log('获取 文章详情');
      dispatch(getArticleById(params.id));
    }
    form.setFieldsValue({
      type: articleDetail.type,
      content: articleDetail.content ? articleDetail.content : '',
      channelId: articleDetail.channelId,
      title: articleDetail.title,
    });
  }, [
    dispatch,
    params.id,
    articleDetail.id,
    articleDetail.type,
    articleDetail.channelId,
    articleDetail.title,
    articleDetail.content,
    form,
  ]);

  // 文件上传成功回调
  const onUploadChange = (info) => {
    // console.log('文件上传回调', info);
    setFileList(info.fileList);
    setFileListStore(info.fileList);
  };

  // 用户切换图片选择
  const handleTypeChange = (e) => {
    console.log(typeof e.target.value);
    setMaxCount(e.target.value);
    if (e.target.value === '1' && fileListStore.length > 0) {
      setFileList([fileListStore[0]]);
    } else {
      setFileList([...fileListStore]);
    }
  };

  const onFinish = (values) => {
    // 判断图片数量和用户的选择是否一致
    if (values.type !== fileList.length) {
      return message.warn('封面数量和选择不一致');
    }
    // 发布文章
    dispatch(
      publishArticle({
        values,
        fileList,
        publishType,
        articleId: params.id,
      })
    );

    // 发布完成后跳转到文章列表页
    history.push('/home/article');
  };

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home/index">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {params.id ? '修改文章' : '发布文章'}
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          initialValues={{ content: '' }}
          onFinish={onFinish}
          labelCol={{ span: 1 }}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channelId"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Channel width={400} />
            {/* <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              <Option value={0}>推荐</Option>
            </Select> */}
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type" onChange={handleTypeChange}>
              <Radio.Group>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
                {/* <Radio value={-1}>自动</Radio> */}
              </Radio.Group>
            </Form.Item>
            {maxCount > 0 && (
              <Upload
                className="avatar-uploader"
                name="image"
                listType="picture-card"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                maxCount={maxCount}
                fileList={fileList}
                onChange={onUploadChange}
              >
                <div>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
            wrapperCol={{ span: 16 }}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            ></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 1 }}>
            <Space>
              <Button
                size="large"
                type="primary"
                htmlType="submit"
                onClick={() => setPublishType('publish')}
              >
                {params.id ? '修改文章' : '发布文章'}
              </Button>
              <Button
                size="large"
                htmlType="submit"
                onClick={() => setPublishType('draft')}
              >
                存入草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
